﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Applay
{
    public class AuthorizeAttribute : ServiceFilterAttribute, IAuthorizationFilter
    {
        private string users;
        private string roles;
        private string[] usersSplit = new string[0];
        private string[] rolesSplit = new string[0];

        public void OnAuthorize(AuthorizationContext context)
        {
            context.IsAuthorized = (this.usersSplit.Length <= 0 || this.usersSplit.Contains(context.User.Identity.Name, StringComparer.OrdinalIgnoreCase))
                && (this.rolesSplit.Length <= 0 || this.rolesSplit.Any(new Func<string, bool>(context.User.IsInRole)));
        }

        public string Users
        {
            get { return this.users; }
            set
            {
                this.users = value;
                this.usersSplit = SplitString(value);
            }
        }

        public string Roles
        {
            get { return this.roles; }
            set
            {
                this.roles = value;
                this.rolesSplit = SplitString(value);
            }
        }

        private static string[] SplitString(string original)
        {
            if (string.IsNullOrEmpty(original))
            {
                return new string[0];
            }

            IEnumerable<string> source =
                from piece in original.Split(new char[]{','})
                let trimmed = piece.Trim()
                where !string.IsNullOrEmpty(trimmed)
                select trimmed;

            return source.ToArray<string>();
        }
    }
}
